package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.model.param.VoucherParams
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.ActivitySubmitProofBinding
import com.gexiaobao.pigeon.ui.adapter.GridImageAdapter
import com.gexiaobao.pigeon.ui.view.recycleview.FullyGridLayoutManager
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.luck.picture.lib.basic.IBridgeViewLifecycle
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DensityUtil
import com.luck.picture.lib.utils.MediaUtils
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.finish
import java.io.File


/**
 * @Author      : hxw
 * @Date        : 2024/5/25 10:24
 * @Describe    : 上传凭证
 */
class ActivitySubmitProof : BaseActivity<OrgDetailViewModel, ActivitySubmitProofBinding>() {

    private val maxSelectNum = 3
    private lateinit var mAdapter: GridImageAdapter
    private val mData: List<LocalMedia> = arrayListOf()
    private lateinit var pop: PopupWindow
    private var voucherFile1: File? = null
    private var voucherFile2: File? = null
    private var voucherFile3: File? = null
    private var pictureResult: ArrayList<LocalMedia> = arrayListOf()
    private var mId: Int = 0
    private var mActivityType = ""

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("上传凭证") {
            finish()
        }

        mId = intent.getIntExtra("id", 0)
        mActivityType = intent.getStringExtra("activity").toString()

        initAdapter()

    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvSubmitProof) {
            when (it) {
                mDatabind.tvSubmitProof -> {
                    upLoadVoucherPic()
                }
            }
        }
    }

    private fun upLoadVoucherPic() {
        val remitter = mDatabind.etProofName.text.toString().trim()
        if (remitter.isEmpty()) {
            RxToast.showToast("请输入汇款人姓名")
            return
        }
        if (mAdapter.data.size == 1) {
            voucherFile1 = File(mAdapter.data[0].realPath)
        }
        if (mAdapter.data.size == 2) {
            voucherFile1 = File(mAdapter.data[0].realPath)
            voucherFile2 = File(mAdapter.data[1].realPath)
        }
        if (mAdapter.data.size == 3) {
            voucherFile1 = File(mAdapter.data[0].realPath)
            voucherFile2 = File(mAdapter.data[1].realPath)
            voucherFile3 = File(mAdapter.data[2].realPath)
        }
        if (voucherFile1 == null && voucherFile2 == null && voucherFile3 == null) {
            RxToast.showToast("请上传凭证照片")
            return
        }
        showLoading(getString(R.string.loading))
        val param = VoucherParams(
            voucher1 = voucherFile1,
            voucher2 = voucherFile2,
            voucher3 = voucherFile3,
            remitter = remitter,
            id = mId
        )
        if (mActivityType == "ActivityMakeAnAppointment") {
            mViewModel.uploadVoucher(param, "ActivityMakeAnAppointment")
        } else {
            mViewModel.uploadVoucher(param, "ActivityVisitByAppointment")
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 上传凭证 */
        mViewModel.voucherResult.observe(this) {
            if (it.isSuccess) {
                val intent = Intent()
                intent.putExtra("isRefresh", true)
                finish(intent)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    private fun initAdapter() {
        val manager = FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        mDatabind.recycler.layoutManager = manager
        mDatabind.recycler.addItemDecoration(GridSpacingItemDecoration(4, DensityUtil.dip2px(this, 8f), false))
        mAdapter = GridImageAdapter(this, mData)
        mAdapter.selectMax = maxSelectNum
        mDatabind.recycler.adapter = mAdapter

        mAdapter.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                // 预览图片、视频、音频
                PictureSelector.create(this@ActivitySubmitProof)
                    .openPreview()
                    .setImageEngine(GlideEngine.createGlideEngine())
//                    .setAttachViewLifecycle(object : IBridgeViewLifecycle {
//                        override fun onViewCreated(fragment: Fragment, view: View, savedInstanceState: Bundle) {}
//
//                        override fun onDestroy(fragment: Fragment) {}
//                    })
                    .startActivityPreview(position, true, mAdapter.data)
            }

            override fun openPicture() {
                showPop()
            }

        })
    }

    private fun showPop() {
        hideSoftKeyboard(this@ActivitySubmitProof)
        val bottomView = View.inflate(this, R.layout.layout_bottom_dialog, null)
        val mAlbum = bottomView.findViewById<TextView>(R.id.tv_album)
        val mCamera = bottomView.findViewById<TextView>(R.id.tv_camera)
        val mCancel = bottomView.findViewById<TextView>(R.id.tv_cancel)

        pop = PopupWindow(bottomView, -1, -2)
        pop.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        pop.isOutsideTouchable = true
        pop.isFocusable = true
        val lp = window.attributes
        lp.alpha = 0.5f
        window.attributes = lp
        pop.setOnDismissListener {
            val lp = window.attributes
            lp.alpha = 1f
            window.attributes = lp
        }
        pop.animationStyle = R.style.main_menu_photo_anim
        pop.showAtLocation(window.decorView, Gravity.BOTTOM, 0, 0)

        @SuppressLint("NotifyDataSetChanged")
        val clickListener = View.OnClickListener { view ->
            when (view.id) {
                R.id.tv_album ->//相册
                    PictureSelector.create(this)
                        .openGallery(SelectMimeType.ofImage())
                        .setMaxSelectNum(maxSelectNum)
                        .setMinSelectNum(1)
                        .isDisplayCamera(false)//是否打开摄像按钮
                        .isMaxSelectEnabledMask(true)//是否显示蒙层（达到最大可选数量）
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setCompressEngine(PictureUtil.getCompressFileEngine())
                        .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
                        .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
                        .setImageSpanCount(3)
                        .setSelectionMode(SelectModeConfig.MULTIPLE)
                        .setSelectedData(mAdapter.data)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: ArrayList<LocalMedia>?) {
                                analyticalSelectResults(result)
                            }

                            override fun onCancel() {}
                        })

                R.id.tv_camera ->//拍照
                    PictureSelector.create(this)
                        .openCamera(SelectMimeType.ofImage())
                        .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
                        .setCompressEngine(PictureUtil.getCompressFileEngine())
                        .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
                        .setSelectedData(mAdapter.data)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: ArrayList<LocalMedia>?) {
                                analyticalSelectResults(result)
                            }

                            override fun onCancel() {}
                        })

                R.id.tv_cancel -> {
                    closePopupWindow()
                }
            }
            closePopupWindow()
        }

        mAlbum.setOnClickListener(clickListener)
        mCamera.setOnClickListener(clickListener)
        mCancel.setOnClickListener(clickListener)
    }

    private fun analyticalSelectResults(result: ArrayList<LocalMedia>?) {
        if (result != null) {
            pictureResult.addAll(result)
            for (media in result) {
                if (media.width == 0 || media.height == 0) {
                    if (PictureMimeType.isHasImage(media.mimeType)) {
                        val imageExtraInfo = MediaUtils.getImageSize(this, media.path)
                        media.width = imageExtraInfo.width
                        media.height = imageExtraInfo.height
                    } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                        val videoExtraInfo = MediaUtils.getVideoSize(this, media.path)
                        media.width = videoExtraInfo.width
                        media.height = videoExtraInfo.height
                    }
                }
            }
            runOnUiThread {
                val isMaxSize = result.size == mAdapter.selectMax
                val oldSize: Int = mAdapter.data.size
                mAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
                mAdapter.data.clear()
                mAdapter.data.addAll(result)
                mAdapter.notifyItemRangeInserted(0, result.size)
            }
        }
    }

    private fun closePopupWindow() {
        if (::pop.isInitialized && pop.isShowing) {
            pop.dismiss()
        }
    }
}